package com.yibo.yunpicture.application.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yibo.yunpicture.domain.picture.service.PictureDomainService;
import com.yibo.yunpicture.infrastructure.api.aliyunai.model.CreateOutPaintingTaskResponse;
import com.yibo.yunpicture.infrastructure.exception.ErrorCode;
import com.yibo.yunpicture.infrastructure.exception.ThrowUtils;
import com.yibo.yunpicture.interfaces.dto.picture.*;
import com.yibo.yunpicture.domain.picture.entity.Picture;
import com.yibo.yunpicture.domain.user.entity.User;
import com.yibo.yunpicture.interfaces.vo.picture.PictureVO;
import com.yibo.yunpicture.interfaces.vo.user.UserVO;
import com.yibo.yunpicture.application.service.PictureApplicationService;
import com.yibo.yunpicture.infrastructure.mapper.PictureMapper;
import com.yibo.yunpicture.application.service.UserApplicationService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author AdminMYB
 * @description 针对表【picture(图片)】的数据库操作Service实现
 * @createDate 2025-04-25 08:11:00
 */
@Service
@Slf4j
public class PictureApplicationServiceImpl extends ServiceImpl<PictureMapper, Picture>
        implements PictureApplicationService {

    @Resource
    private PictureDomainService pictureDomainService;

    @Resource
    private UserApplicationService userApplicationService;

    @Override
    public PictureVO uploadPicture(Object inputSource, PictureUploadDTO pictureUploadDTO, User loginUser) {
        return pictureDomainService.uploadPicture(inputSource, pictureUploadDTO, loginUser);
    }

    /**
     * 获取单个图片的封装类
     *
     * @param picture
     * @param request
     * @return
     */
    @Override
    public PictureVO getPictureVO(Picture picture, HttpServletRequest request) {
        // 对象转封装类
        PictureVO pictureVO = PictureVO.objToVo(picture);
        // 关联查询用户信息
        Long userId = picture.getUserId();
        if (userId != null && userId > 0) {
            User user = userApplicationService.getUserById(userId);
            UserVO userVO = new UserVO();
            BeanUtil.copyProperties(user, userVO);
            pictureVO.setUser(userVO);
        }
        return pictureVO;
    }

    /**
     * 分页获取图片封装
     */
    @Override
    public Page<PictureVO> getPictureVOPage(Page<Picture> picturePage, HttpServletRequest request) {
        List<Picture> pictureList = picturePage.getRecords();
        Page<PictureVO> pictureVOPage = new Page<>(picturePage.getCurrent(), picturePage.getSize(), picturePage.getTotal());
        if (CollUtil.isEmpty(pictureList)) {
            return pictureVOPage;
        }
        //将对象列表 => 封装对象列表
        List<PictureVO> pictureVOList = pictureList.stream().map(PictureVO::objToVo).collect(Collectors.toList());
        //1.关联查询用户信息
        //只需要查询到一个用户Id就可以
        Set<Long> userIdList = pictureVOList.stream().map(PictureVO::getUserId).collect(Collectors.toSet());
        Map<Long, List<User>> userIdUserListMap = userApplicationService.listByIds(userIdList).stream().collect(Collectors.groupingBy(User::getId));
        //2.填充信息
        pictureVOList.forEach(pictureVO -> {
            Long userId = pictureVO.getUserId();
            User user = null;
            if (userIdUserListMap.containsKey(userId)) {
                user = userIdUserListMap.get(userId).get(0);
            }
            UserVO userVO = new UserVO();
            BeanUtil.copyProperties(user, userVO);
            pictureVO.setUser(userVO);
        });
        pictureVOPage.setRecords(pictureVOList);
        return pictureVOPage;
    }

    /**
     * 删除图片
     */
    @Override
    public void deletePicture(long pictureId, User loginUser) {
        pictureDomainService.deletePicture(pictureId, loginUser);
    }

    /**
     * 编辑图片
     */
    public void editPicture(Picture picture, User loginUser) {
       pictureDomainService.editPicture(picture, loginUser);
    }

    /**
     * 编写图片校验方法
     *
     * @param picture
     */
    @Override
    public void validPicture(Picture picture) {
        ThrowUtils.throwIf(picture == null, ErrorCode.PARAMS_ERROR);
        picture.validPicture();
    }


    @Override
    public QueryWrapper<Picture> getQueryWrapper(PictureQueryDTO pictureQueryDTO) {
        return pictureDomainService.getQueryWrapper(pictureQueryDTO);
    }

    @Override
    public void doPictureReview(PictureReviewDTO pictureReviewDTO, User loginUser) {
        pictureDomainService.doPictureReview(pictureReviewDTO, loginUser);
    }

    /**
     * 填充图片审核参数
     *
     * @param picture
     * @param loginUser
     */
    @Override
    public void fillReviewParam(Picture picture, User loginUser) {
        pictureDomainService.fillReviewParam(picture, loginUser);
    }

    /**
     * 批量上传图片
     *
     * @param pictureUploadByBatchDTO
     * @param loginUser
     * @return
     */
    @Override
    public Integer uploadPictureBatch(PictureUploadByBatchDTO pictureUploadByBatchDTO, User loginUser) {
        return pictureDomainService.uploadPictureBatch(pictureUploadByBatchDTO, loginUser);
    }

    /**
     * 清理对象存储上的文件
     *
     * @param oldPicture
     */

    @Async
    @Override
    public void clearPictureFile(Picture oldPicture) {
        pictureDomainService.clearPictureFile(oldPicture);
    }

    /**
     * 如果有空间id需要校验，额外的权限
     *
     * @param loginUser
     * @param oldPicture
     */
    @Override
    public void checkPictureAuth(User loginUser, Picture oldPicture) {
        pictureDomainService.checkPictureAuth(loginUser, oldPicture);
    }

    /**
     * 根据颜色搜索图片
     *
     * @param spaceId
     * @param picColor
     * @param loginUser
     * @return
     */
    @Override
    public List<PictureVO> searchPictureByColor(Long spaceId, String picColor, User loginUser) {
        return pictureDomainService.searchPictureByColor(spaceId, picColor, loginUser);
    }

    @Override
    public void editPictureByBatch(PictureEditByBatchDTO pictureEditByBatchDTO, User loginUser) {
        pictureDomainService.editPictureByBatch(pictureEditByBatchDTO, loginUser);
    }

    @Override
    public CreateOutPaintingTaskResponse createPictureOutPaintingTask(CreatePictureOutPaintingTaskDTO createPictureOutPaintingTaskDTO, User loginUser){
        return pictureDomainService.createPictureOutPaintingTask(createPictureOutPaintingTaskDTO, loginUser);
    }

    /*@Transactional(rollbackFor = Exception.class)
    @Override
    public void batchEditPictureMetadata(PictureEditByBatchDTO pictureEditByBatchDTO, User loginUser){
        List<Long> pictureIdList = pictureEditByBatchDTO.getPictureIdList();
        Long spaceId = pictureEditByBatchDTO.getSpaceId();
        String category = pictureEditByBatchDTO.getCategory();
        List<String> tags = pictureEditByBatchDTO.getTags();
        // 批量重命名
        String nameRule = pictureEditByBatchDTO.getNameRule();
        // 1. 校验参数
        ThrowUtils.throwIf(spaceId == null || CollUtil.isEmpty(pictureIdList), ErrorCode.PARAMS_ERROR);
        ThrowUtils.throwIf(loginUser == null, ErrorCode.NO_AUTH_ERROR);
        // 2. 空间权限校验
        Space space = spaceService.getById(spaceId);
        ThrowUtils.throwIf(space == null, ErrorCode.PARAMS_ERROR);
        if (!space.getUserId().equals(loginUser.getId())) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        // 3. 查询指定图片，仅选择需要的字段
        List<Picture> pictureList = this.lambdaQuery()
                .select(Picture::getId, Picture::getUserId)
                .eq(Picture::getSpaceId, spaceId)
                .in(Picture::getId, pictureIdList)
                .list();
        if (pictureList.isEmpty()) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "指定的图片不存在或不属于该空间");
        }
        // 4. 分批处理避免长事务
        int batchSize = 100;
        List<CompletableFuture<Void>> futures = new ArrayList<>();
        for (int i = 0; i < pictureList.size(); i += batchSize) {
            List<Picture> batch = pictureList.subList(i, Math.min(i + batchSize, pictureList.size()));

            // 异步处理每批数据
            CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
                batch.forEach(picture -> {
                    // 编辑分类和标签
                    if(StrUtil.isNotBlank(category)){
                        picture.setCategory(category);
                    }
                    if (ObjUtil.isNotEmpty(tags)) {
                        picture.setTags(JSONUtil.toJsonStr(tags));
                    }
                });
                // 5. 批量重命名
                fillPictureWithNameRule(pictureList, nameRule);
                // 6. 批量更新
                boolean result = this.updateBatchById(pictureList);
                ThrowUtils.throwIf(!result, ErrorCode.SYSTEM_ERROR);
            },customExecutor);
            futures.add(future);
        }
        // 等待所有异步任务完成
        CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).join();
    }
     */
}




